<script setup lang="ts">
import axios from 'axios'
import { ref } from 'vue'

let abort: AbortController

const progress = ref(0)

const downloadBtn = () => {
  // 中断控制器
  abort = new AbortController()
  axios({
    method: 'GET', // 请求方式
    url: 'http://localhost:3000/video', // 请求地址
    responseType: 'arraybuffer', // 响应类型
    signal: abort.signal, // 🎉中断控制器标识
    // 下载进度
    onDownloadProgress(e) {
      // 计算进度百分比
      progress.value = Math.round((e.loaded / e.total!) * 100)
    }
  })
    .then((res) => {
      console.log(res)
    })
    .catch(() => {})
}

const abortBtn = () => {
  // 请求中断
  abort.abort()
}
</script>

<template>
  <div>
    <button class="download" @click="downloadBtn">下载视频</button>
    <button class="abort" @click="abortBtn">中止下载</button>
    <div class="progress-bar">
      <div class="progress" :style="{ width: progress + '%' }"></div>
      {{ progress }}%
    </div>
  </div>
</template>

<style scoped>
.progress-bar {
  height: 20px;
  background-color: #eee;
  margin-top: 10px;
}
.progress {
  width: 0%;
  height: 100%;
  background-color: #4caf50;
  transition: width 0.2s linear;
}
</style>
